package cn.mw.cmdb.service.impl;

import cn.mw.cmdb.exception.CreateQRCodeException;
import cn.mw.cmdb.param.CodeModel;
import com.google.zxing.WriterException;
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.*;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.List;
import java.util.Map;

import static cn.mw.cmdb.entity.InputDataAuth.OrgNameKey;
import static cn.mw.cmdb.service.impl.InstanceViewImpl.*;
import static cn.mw.cmdb.util.QR_Code.createCodeImage;
import static org.apache.commons.lang3.ObjectUtils.isEmpty;
import static org.apache.commons.lang3.ObjectUtils.isNotEmpty;

/**
 * 根据模板填充数据及图片，动态生成数据列表
 */
@Slf4j
public class CreatePdfQrCodeTable {

    /**
     * 标签打印pdf
     *
     * @param res
     */
    public static void labelPrinting(List<Map> list, HttpServletResponse res) throws Exception {
        PdfContentByte waterMar;
        ServletOutputStream outputStream = null;
        FileInputStream in = null;
        Document document = new Document();

        //文档对象  实现A4纸页面
        //设置文档的页边距就是距离页面边上的距离，分别为：左边距，右边距，上边距，下边距
        document.setMargins(4, 4, 3, 3);
        //这个是生成破pdf的位置以及名称
//            String fileName = System.currentTimeMillis() + ".pdf";
//            PdfWriter.getInstance(document, new FileOutputStream(fileName));
        File pdfFile = new File("资产二维码标签.pdf");
        FileOutputStream fileOutputStream = new FileOutputStream(pdfFile);
        PdfWriter writer = PdfWriter.getInstance(document, fileOutputStream);
        writer.setUserunit(10f);
        //打开文档
        document.open();
        //使用字体，正文字体
        Font font = new Font(BaseFont.createFont("STSongStd-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED), 5, Font.BOLD);
        Font minFont = new Font(BaseFont.createFont("STSongStd-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED), 4, Font.BOLD);
        InputStream scbLogo = CreatePdfQrCodeTable.class.getClassLoader().getResourceAsStream("images/scLogo.png");
        BufferedImage bg = ImageIO.read(scbLogo);
        ByteArrayOutputStream outs = new ByteArrayOutputStream();
        ImageIO.write(bg, "png", outs);
        Image scbImage = Image.getInstance(outs.toByteArray());
        scbImage.scaleAbsolute(6, 6);
        //mw_asset_coding
        //循环多页
        for (Map m : list) {
            //设置每页大小  //196   112    ->   490.0F, 280
            PdfRectangle rect = new PdfRectangle((int) (70 / 25.4 * 72), (int) (40 / 25.4 * 72));
            document.setPageSize(rect.getRectangle());
            //创建新的一页
            document.newPage();
            // -------------------二维码图片 ----------------
            ByteArrayOutputStream out = new ByteArrayOutputStream();
//                ImageIO.write(QRCodeUtils.drawQRCodeWithContent(getMapValue(m, "materialsLabel")), "png", out);


            CodeModel codeInfo = new CodeModel();
            codeInfo.setContents(getMapValue(m, qrTextKey));
            codeInfo.setWidth(1000);
            codeInfo.setHeight(1000);
            try {
                BufferedImage codeImage = createCodeImage(codeInfo);
                ImageIO.write(codeImage, "png", out);
            } catch (WriterException e) {
                log.error("createCodeImage to fail::" + e);
                if (e.getMessage().indexOf("Data too big") != -1) {
                    throw new CreateQRCodeException("qrcode_data_big_error");
                }

            }
            Image image = Image.getInstance(out.toByteArray());
            image.scaleAbsolute(50f, 50f);
//                image.setScaleToFitHeight(true);
            // 标题与Logo
            Font font1 = new Font(BaseFont.createFont("STSongStd-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED), 8, Font.BOLD);
            PdfPTable table = new PdfPTable(3);
            table.setWidthPercentage(100.25f); // Width 100%

            float[] columnWidthsLog = {6f, 16f, 6f};
            table.setWidths(columnWidthsLog);


            PdfPCell titleCell = getTitlePdfPCell("四川银行 ", font1, 0f, 0f);
            PdfPCell emptyCell = getTitlePdfPCell(" ", font1, 0f, null);

            // 添加 SCB 字符串和 logo
            PdfPCell scbCell = new PdfPCell();
            scbCell.setBorderWidthRight(Rectangle.NO_BORDER);
            Phrase scbPhrase = new Phrase("SCB ", font);
            Chunk logoChunk = new Chunk(scbImage, 0, -1);
            scbPhrase.add(logoChunk);
            scbCell.setBorderColor(BaseColor.BLACK);
            scbCell.setHorizontalAlignment(Element.ALIGN_CENTER);
            scbCell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            scbCell.addElement(scbPhrase);
            scbCell.setPaddingBottom(6f);
            scbCell.setPaddingLeft(6f);

            // 添加到嵌套表格中
            table.addCell(scbCell);

//                // 添加 四川银行 标题
//                PdfPCell titleCell = new PdfPCell(new Phrase("四川银行", font1));
//                titleCell.setHorizontalAlignment(Element.ALIGN_CENTER);
//                titleCell.setVerticalAlignment(Element.ALIGN_MIDDLE);
//                titleCell.setBorderWidthRight(Rectangle.NO_BORDER);
//                titleCell.setBorderWidthLeft(Rectangle.NO_BORDER);
//                titleCell.setBorderWidthBottom(Rectangle.NO_BORDER);
//                titleCell.setFixedHeight(15f);
            table.addCell(titleCell);
//                //空数据
//                PdfPCell emptyCell = new PdfPCell();
//                emptyCell.setHorizontalAlignment(Element.ALIGN_CENTER);
//                emptyCell.setVerticalAlignment(Element.ALIGN_MIDDLE);
//                emptyCell.setBorderWidthLeft(Rectangle.NO_BORDER);
//                emptyCell.setBorderWidthBottom(Rectangle.NO_BORDER);
//                emptyCell.setFixedHeight(15f);
            table.addCell(emptyCell);

            document.add(table);

//                table.setWidthPercentage(100);
//                table.addCell(getTitlePdfPCell("SCB", font1,null,0f));
//                table.addCell(getTitlePdfPCell("", minFont,0f,0f,scbImage));
//                table.addCell(getTitlePdfPCell("四川银行 ",font1,0f,null));
//                document.add(table);

//
//                float[] columnWidthsTitle = {0.3f,0.3f,2.4f};
//                table.setWidths(columnWidthsTitle);
//
//                PdfPCell scbTextCell = new PdfPCell();
//                scbTextCell.addElement(new Phrase("SCB ",font1));
//                scbTextCell.setBorderWidthRight(PdfPCell.NO_BORDER);
////                scbTextCell.setBorderWidth(2f);
//                scbTextCell.setHorizontalAlignment(Element.ALIGN_CENTER);
//                scbTextCell.setVerticalAlignment(Element.ALIGN_MIDDLE);
//                table.addCell(scbTextCell);
//
//                PdfPCell scbLogoCell = new PdfPCell();
//                scbLogoCell.addElement(scbImage);
//                scbLogoCell.setBorderWidthLeft(PdfPCell.NO_BORDER);
//                scbLogoCell.setBorderWidthRight(PdfPCell.NO_BORDER);
////                scbTextCell.setBorderWidth(2f);
//                scbTextCell.setHorizontalAlignment(Element.ALIGN_CENTER);
//                scbTextCell.setVerticalAlignment(Element.ALIGN_MIDDLE);
//                table.addCell(scbLogoCell);
//
//
//                PdfPCell titleCell = new PdfPCell(new Phrase("四川银行 ",font1));
//                titleCell.setBorderWidthLeft(PdfPCell.NO_BORDER);
//                titleCell.setHorizontalAlignment(Element.ALIGN_CENTER);
//                titleCell.setVerticalAlignment(Element.ALIGN_MIDDLE);
////                scbTextCell.setBorderWidth(2f);
////                scbTextCell.setHorizontalAlignment(Element.ALIGN_CENTER);
////                scbTextCell.setVerticalAlignment(Element.ALIGN_MIDDLE);
//
//                PdfPCell titleCell = getTitlePdfPCell("四川银行", font1, 1, 1);
//                table.addCell(titleCell);

//                document.add(table);


//                Font font1 = new Font(BaseFont.createFont("STSongStd-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED), 8, Font.BOLD);
//                PdfPTable table = new PdfPTable(1);
//                table.setWidthPercentage(100); // Width 100%
//                float[] columnWidthsTitle = {28f};
//                table.setPaddingTop(4f);
//                table.setHorizontalAlignment(Element.ALIGN_CENTER);
//                table.setWidths(columnWidthsTitle);
////                table.addCell(getPdfPCell("四川银行", font));
//                table.addCell(getTitlePdfPCell("四川银行", font1, 4, 1));
//                document.add(table);
//28
            //5 10 7 6
            //5  16 7
            //5   13
            table = new PdfPTable(4);
            float[] columnWidths = {5f, 10f, 7f, 6f};
            table.setWidths(columnWidths);
            table.setWidthPercentage(100);
            table.addCell(getPdfPCell("实物标签号", font));
            table.addCell(getPdfPCell(getMapValue(m, mwAssetCodingKey), font));
            table.addCell(getPdfPCell("开始使用日期", font));
            table.addCell(getPdfPCell(getMapValue(m, mwFacilityUseDateKey), font));
            document.add(table);

            table = new PdfPTable(2);
            float[] columnWidthsName = {5f, 23f};
            table.setWidths(columnWidthsName);
            table.setWidthPercentage(100);
            table.addCell(getPdfPCell("资产名称", font));
            table.addCell(getPdfPCell(getMapValue(m, mwInstanceNameKey), font));
            document.add(table);

            table = new PdfPTable(3);
            float[] columnWidths2 = {5.06f, 9.2f, 7f};
            table.setWidths(columnWidths2);
            table.setWidthPercentage(100);
            table.addCell(getPdfPCell("品牌", font));
            table.addCell(getPdfPCell(getMapValue(m, mwAssetBrandKey), font, 2, 1));
            table.addCell(getPdfPCell("型号", font));
            table.addCell(getPdfPCell(getMapValue(m, mwAssetTypeKey), font, 2, 1));
            table.addCell(getPdfPCell("序列号", font));
            table.addCell(getPdfPCell(getMapValue(m, mwProductIdKey), font, 2, 1));
            table.addCell(getPdfPCell("采购日期", font));
            table.addCell(getPdfPCell(getMapValue(m, mwPurchaseDateKey), font, 2, 1));
            table.addCell(getPdfPCell("供应商", font));
            table.addCell(getPdfPCell(getMapValue(m, mwSupplierKey), font, 2, 1));

            PdfPTable mergeTable = new PdfPTable(2);
            float[] columnWidths3 = {3f, 1f};
            mergeTable.setWidths(columnWidths3);
            mergeTable.setWidthPercentage(100);
            PdfPCell leftCell = new PdfPCell(table);
            mergeTable.addCell(leftCell);

            //合并行
            PdfPCell rightCell = new PdfPCell();
            rightCell.setBorderColor(BaseColor.BLACK);
            rightCell.setHorizontalAlignment(Element.ALIGN_CENTER);
            rightCell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            rightCell.setPadding(2f);
//                rightCell.setFixedHeight(51.5f);
            rightCell.setImage(image);
            mergeTable.addCell(rightCell);
            document.add(mergeTable);

            table = new PdfPTable(2);
            float[] columnWidths4 = {5f, 23f};
            table.setWidths(columnWidths4);
            table.setWidthPercentage(100);
            table.addCell(getPdfPCell("资产类别", font));
            table.addCell(getPdfPCell(getMapValue(m, MW_ASSET_TYPE_Key), font));
            document.add(table);

            table = new PdfPTable(2);
            float[] columnWidths5 = {5f, 23f};
            table.setWidths(columnWidths5);
            table.setWidthPercentage(100);
            table.addCell(getPdfPCell("机构部门", font));
            table.addCell(getPdfPCell(getMapValue(m, OrgNameKey), font));
            document.add(table);
        }
        try {
            document.close();
            in = new FileInputStream(pdfFile);
            outputStream = res.getOutputStream();
            byte[] buff = new byte[1024];
            int n;
            while ((n = in.read(buff)) != -1) {
                //将字节数组的数据全部写入到输出流中
                outputStream.write(buff, 0, n);
            }
            //强制将缓存区的数据进行输出
            outputStream.flush();
            in.close();
            //关流
            outputStream.close();
        } catch (Exception e) {
            log.error("labelPrinting fail to", e);
        } finally {
            try {
                document.close();
                in.close();
                outputStream.close();
            } catch (IOException e) {
                log.error("close outputStream fail to", e);
            }
        }
    }

    public static PdfPCell getPdfPCell(String value, Font font) {
        return getPdfPCell(value, font, 0, 0, null);
    }

    public static PdfPCell getPdfPCell(String value, Font font, Image image) {
        return getPdfPCell(value, font, 0, 0, image);
    }

    public static PdfPCell getTitlePdfPCell(String value, Font font, Float left, Float right, Image image) {
        return getTitlePdfPCell(value, font, left, right, 0, 0, image);
    }

    public static PdfPCell getTitlePdfPCell(String value, Font font, Float left, Float right) {
        return getTitlePdfPCell(value, font, left, right, 0, 0, null);
    }

    public static PdfPCell getTitlePdfPCell(String value, Font font, Float left, Float right, int colspan, int rowspan) {
        return getTitlePdfPCell(value, font, left, right, colspan, rowspan, null);
    }

    public static PdfPCell getPdfPCell(String value, Font font, int colspan, int rowspan) {
        return getPdfPCell(value, font, colspan, rowspan, null);
    }

    public static PdfPCell getTitlePdfPCell(String value, Font font, Float left, Float right, int colspan, int rowspan, Image image) {
        PdfPCell cell = new PdfPCell(new Phrase(value, font));
        cell.setUseBorderPadding(true);
        cell.setBorderColor(BaseColor.BLACK);
        if (left != null) {
            cell.setBorderWidthLeft(left);
        }
        if (right != null) {
            cell.setBorderWidthRight(right);
        }
        cell.setPaddingBottom(4f);
        cell.setFixedHeight(8f);
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        cell.setColspan(colspan);
        cell.setRowspan(rowspan);
        if (isNotEmpty(image)) {
            cell.setImage(image);
        }
        return cell;
    }

    public static PdfPCell getPdfPCell(String value, Font font, int colspan, int rowspan, Image image) {
        PdfPCell cell = new PdfPCell(new Phrase(value, font));
        cell.setUseBorderPadding(true);
        cell.setBorderColor(BaseColor.BLACK);
        cell.setPaddingBottom(2f);
        cell.setFixedHeight(10f);
        cell.setHorizontalAlignment(Element.ALIGN_LEFT);
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        cell.setColspan(colspan);
        cell.setRowspan(rowspan);
        if (isNotEmpty(image)) {
            cell.setImage(image);
        }
        return cell;
    }

    public static String getMapValue(Map map, String key) {
        return isEmpty(map.get(key)) ? "" : map.get(key).toString();
    }
}
